package com.runrunfast.face.controller;

import com.alibaba.fastjson.JSONObject;
import com.runrunfast.face.service.common.ColourService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * YouBox人脸检测时间回调处理
 *
 * @author YangNing
 */
@Api(description = "人脸检测事件回调")
@RestController
public class CallbackController {

    private static Logger logger = LoggerFactory.getLogger(CallbackController.class);

    @Autowired
    private ColourService colourService;

    @ApiOperation("回调地址")
    @PostMapping("/callback")
    public void callBack(HttpServletRequest request, @RequestBody Map<String, String> map) {
        logger.info("回调开始-------->");
        logger.info("Callback:acceptjson:-------->");
        String acceptjson;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer();
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            acceptjson = sb.toString();
            logger.info(acceptjson);
            JSONObject response = colourService.reportEvent(JSONObject.parseObject(acceptjson));
            logger.info("Event事件上报结果----->: " + response.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("Callback:map:-------->");
        logger.info(JSONObject.toJSONString(map));
        logger.info("回调结束-------->");
    }

    @ApiOperation("模拟回调")
    @PostMapping("/mocCallback")
    public JSONObject mocCallback(String callback) {
        JSONObject jsonObject = JSONObject.parseObject(callback);
        return colourService.reportEvent(jsonObject);
    }

//    @ApiOperation("Thing报文")
//    @PostMapping("/mocThingReport")
//    public JSONObject mocThingReport(String testJson) {
//        JSONObject jsonObject = JSONObject.parseObject(testJson);
//        return colourService.reportThing(jsonObject);
//    }
}
